// src/components/FileList.js
import React, { useState, useEffect } from 'react';
import {
  Table,
  Button,
  Space,
  Card,
  Row,
  Col,
  Modal,
  Form,
  Input,
  Upload,
  message,
  Tooltip,
  Tag,
  Popconfirm
} from 'antd';
import {
  FolderOpenOutlined,
  UploadOutlined,
  EyeOutlined,
  HistoryOutlined,
  DeleteOutlined
} from '@ant-design/icons';
import { useNavigate } from 'react-router-dom';
import axios from 'axios';
import moment from 'moment';

const FileList = () => {
  const [files, setFiles] = useState([]);
  const [loading, setLoading] = useState(false);
  const [uploadModalVisible, setUploadModalVisible] = useState(false);
  const [versionModalVisible, setVersionModalVisible] = useState(false);
  const [selectedFile, setSelectedFile] = useState(null);
  const [versions, setVersions] = useState([]);
  const [form] = Form.useForm();
  const navigate = useNavigate();

  useEffect(() => {
    fetchFiles();
  }, []);

  const fetchFiles = async () => {
    setLoading(true);
    try {
      const response = await axios.get('/api/files');
      setFiles(response.data);
    } catch (error) {
      message.error('获取文件列表失败');
    } finally {
      setLoading(false);
    }
  };

  const fetchVersions = async (fileId) => {
    try {
      const response = await axios.get(`/api/files/${fileId}/versions`);
      setVersions(response.data);
      setVersionModalVisible(true);
    } catch (error) {
      message.error('获取版本列表失败');
    }
  };

  const handleUpload = async (values) => {
    const formData = new FormData();
    formData.append('file', values.file.file);
    formData.append('submitter', values.submitter);
    formData.append('changeDescription', values.changeDescription);

    setLoading(true);
    try {
      await axios.post('/api/upload', formData, {
        headers: {
          'Content-Type': 'multipart/form-data',
        },
      });
      message.success('文件上传成功');
      setUploadModalVisible(false);
      form.resetFields();
      fetchFiles();
    } catch (error) {
      message.error('文件上传失败');
    } finally {
      setLoading(false);
    }
  };

  const handleDeleteFile = async (fileId, fileName) => {
    try {
      await axios.delete(`/api/files/${fileId}`);
      message.success(`文件 "${fileName}" 删除成功`);
      fetchFiles(); // 刷新文件列表
    } catch (error) {
      console.error('删除文件失败:', error);
      if (error.response?.data?.error) {
        message.error(error.response.data.error);
      } else {
        message.error('删除文件失败');
      }
    }
  };

  const fileColumns = [
    {
      title: '文件名',
      dataIndex: 'original_name',
      key: 'original_name',
      ellipsis: {
        showTitle: false,
      },
      render: (text) => (
        <Tooltip placement="topLeft" title={text}>
          {text}
        </Tooltip>
      ),
    },
    {
      title: '创建人',
      dataIndex: 'created_by',
      key: 'created_by',
    },
    {
      title: '版本数',
      dataIndex: 'version_count',
      key: 'version_count',
      render: (count) => <Tag color="blue">{count} 个版本</Tag>,
    },
    {
      title: '最新版本',
      dataIndex: 'latest_version',
      key: 'latest_version',
      render: (version) => <Tag color="green">v{version}</Tag>,
    },
    {
      title: '创建时间',
      dataIndex: 'created_at',
      key: 'created_at',
      render: (time) => moment(time).format('YYYY-MM-DD HH:mm:ss'),
    },
    {
      title: '最后修改',
      dataIndex: 'last_modified',
      key: 'last_modified',
      render: (time) => moment(time).format('YYYY-MM-DD HH:mm:ss'),
    },
    {
      title: '操作',
      key: 'actions',
      render: (_, record) => (
        <Space>
          <Tooltip title="查看最新版本">
            <Button
              type="primary"
              size="small"
              icon={<EyeOutlined />}
              onClick={() => {
                // 需要先获取最新版本ID
                fetchLatestVersionAndView(record.id);
              }}
            >
              查看
            </Button>
          </Tooltip>
          <Tooltip title="版本历史">
            <Button
              size="small"
              icon={<HistoryOutlined />}
              onClick={() => {
                setSelectedFile(record);
                fetchVersions(record.id);
              }}
            >
              历史
            </Button>
          </Tooltip>
          <Tooltip title="删除文件">
            <Popconfirm
              title="确认删除文件"
              description={`确定要删除文件 "${record.original_name}" 吗？此操作将删除该文件的所有版本和相关数据，且不可恢复。`}
              onConfirm={() => handleDeleteFile(record.id, record.original_name)}
              okText="确认删除"
              cancelText="取消"
              okType="danger"
            >
              <Button
                danger
                size="small"
                icon={<DeleteOutlined />}
              >
                删除
              </Button>
            </Popconfirm>
          </Tooltip>
        </Space>
      ),
    },
  ];

  const versionColumns = [
    {
      title: '版本',
      dataIndex: 'version',
      key: 'version',
      render: (version) => <Tag color="blue">v{version}</Tag>,
    },
    {
      title: '提交人',
      dataIndex: 'submitter',
      key: 'submitter',
    },
    {
      title: '变更说明',
      dataIndex: 'change_description',
      key: 'change_description',
      ellipsis: {
        showTitle: false,
      },
      render: (text) => (
        <Tooltip placement="topLeft" title={text}>
          {text}
        </Tooltip>
      ),
    },
    {
      title: '文件大小',
      dataIndex: 'file_size',
      key: 'file_size',
      render: (size) => `${(size / 1024).toFixed(2)} KB`,
    },
    {
      title: '创建时间',
      dataIndex: 'created_at',
      key: 'created_at',
      render: (time) => moment(time).format('YYYY-MM-DD HH:mm:ss'),
    },
    {
      title: '操作',
      key: 'actions',
      render: (_, record) => (
        <Space>
          <Button
            type="primary"
            size="small"
            icon={<EyeOutlined />}
            onClick={() => navigate(`/view/${record.id}`)}
          >
            查看此版本
          </Button>
        </Space>
      ),
    },
  ];

  const fetchLatestVersionAndView = async (fileId) => {
    try {
      const response = await axios.get(`/api/files/${fileId}/versions`);
      if (response.data.length > 0) {
        const latestVersion = response.data[0]; // 第一个就是最新版本
        navigate(`/view/${latestVersion.id}`);
      }
    } catch (error) {
      message.error('获取版本信息失败');
    }
  };

  return (
    <div>
      <Row gutter={[16, 16]} style={{ marginBottom: 24 }}>
        <Col span={24}>
          <Card>
            <div style={{ marginBottom: 16, display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
              <div>
                <FolderOpenOutlined style={{ fontSize: 24, marginRight: 8 }} />
                <span style={{ fontSize: 18, fontWeight: 'bold' }}>文件管理</span>
              </div>
              <Space>
                <Button
                  type="primary"
                  icon={<UploadOutlined />}
                  onClick={() => setUploadModalVisible(true)}
                >
                  上传文件
                </Button>
                <Button onClick={fetchFiles}>刷新</Button>
              </Space>
            </div>
            
            <Table
              columns={fileColumns}
              dataSource={files}
              rowKey="id"
              loading={loading}
              pagination={{
                pageSize: 10,
                showSizeChanger: true,
                showQuickJumper: true,
                showTotal: (total) => `共 ${total} 个文件`,
              }}
            />
          </Card>
        </Col>
      </Row>

      {/* 上传文件模态框 */}
      <Modal
        title="上传Excel文件"
        open={uploadModalVisible}
        onCancel={() => setUploadModalVisible(false)}
        footer={null}
        width={600}
      >
        <Form
          form={form}
          layout="vertical"
          onFinish={handleUpload}
        >
          <Form.Item
            name="file"
            label="选择文件"
            rules={[{ required: true, message: '请选择文件' }]}
            extra="支持 .xlsx, .xls, .csv 格式。如果文件名已存在，将作为新版本上传。"
          >
            <Upload
              beforeUpload={() => false}
              accept=".xlsx,.xls,.csv"
              maxCount={1}
            >
              <Button icon={<UploadOutlined />}>选择Excel文件</Button>
            </Upload>
          </Form.Item>
          
          <Form.Item
            name="submitter"
            label="提交人"
            rules={[{ required: true, message: '请输入提交人' }]}
          >
            <Input placeholder="请输入提交人姓名" />
          </Form.Item>
          
          <Form.Item
            name="changeDescription"
            label="变更说明"
            rules={[{ required: true, message: '请输入变更说明' }]}
          >
            <Input.TextArea
              rows={4}
              placeholder="请描述本次变更的内容..."
            />
          </Form.Item>
          
          <Form.Item>
            <Space>
              <Button type="primary" htmlType="submit" loading={loading}>
                上传
              </Button>
              <Button onClick={() => setUploadModalVisible(false)}>
                取消
              </Button>
            </Space>
          </Form.Item>
        </Form>
      </Modal>

      {/* 版本历史模态框 */}
      <Modal
        title={`版本历史 - ${selectedFile?.original_name}`}
        open={versionModalVisible}
        onCancel={() => setVersionModalVisible(false)}
        footer={null}
        width={1000}
      >
        <Table
          columns={versionColumns}
          dataSource={versions}
          rowKey="id"
          pagination={{
            pageSize: 5,
            showSizeChanger: false,
          }}
        />
      </Modal>
    </div>
  );
};

export default FileList;